import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import find from "./find";
/**
 * 树节点交换顺序，会改变原始数据
 * @param treeNodes
 * @param options
 * @returns
 */
var exchange = function exchange(treeNodes, targetNode, sourceNode, options) {
  var _targetNode$childrenK, _sourceNode$childrenK;
  var _ref = options !== null && options !== void 0 ? options : {},
    _ref$uniqueKey = _ref.uniqueKey,
    uniqueKey = _ref$uniqueKey === void 0 ? 'key' : _ref$uniqueKey,
    _ref$childrenKey = _ref.childrenKey,
    childrenKey = _ref$childrenKey === void 0 ? 'children' : _ref$childrenKey;
  var realTargetNode = find(treeNodes, function (node) {
    return node[uniqueKey] === targetNode[uniqueKey];
  }, {
    childrenKey: childrenKey
  });
  var realSourceNode = find(treeNodes, function (node) {
    return node[uniqueKey] === sourceNode[uniqueKey];
  }, {
    childrenKey: childrenKey
  });
  if (!realTargetNode) {
    throw new Error('targetNode is not existed');
  }
  if (!realSourceNode) {
    throw new Error('source is not existed');
  }
  if ((_targetNode$childrenK = targetNode[childrenKey]) !== null && _targetNode$childrenK !== void 0 && _targetNode$childrenK.length && find([targetNode], function (node) {
    return node[uniqueKey] === sourceNode[uniqueKey];
  }, {
    childrenKey: childrenKey
  })) {
    throw new Error("sourceNode cannot be in targetNode's children");
  }
  if ((_sourceNode$childrenK = sourceNode[childrenKey]) !== null && _sourceNode$childrenK !== void 0 && _sourceNode$childrenK.length && find([sourceNode], function (node) {
    return node[uniqueKey] === targetNode[uniqueKey];
  }, {
    childrenKey: childrenKey
  })) {
    throw new Error("targetNode cannot be in sourceNode's children");
  }

  // 以免 children 等持有相同的引用
  var sourceNodeTemp = _objectSpread({}, sourceNode);
  var targetNodeTemp = _objectSpread({}, targetNode);
  Object.keys(sourceNodeTemp).map(function (key) {
    realTargetNode[key] = sourceNodeTemp[key];
  });
  Object.keys(targetNodeTemp).map(function (key) {
    realSourceNode[key] = targetNodeTemp[key];
  });

  // 目标节点的 children 已被复制给源节点，删除目标节点的 children
  if (childrenKey in targetNodeTemp && !(childrenKey in sourceNodeTemp)) {
    delete realTargetNode[childrenKey];
  }
  if (childrenKey in sourceNodeTemp && !(childrenKey in targetNodeTemp)) {
    delete realSourceNode[childrenKey];
  }
  return treeNodes;
};
export default exchange;